'''
Created on Mar 14, 2010

@author: rax
'''

from django.contrib.auth.forms import UserCreationForm
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore
from django.core.urlresolvers import RegexURLResolver
from django.http import Http404,  HttpRequest



""" Defines a patter for assigning values to the urls.
    Patterns are applied in the exact order in which they
    are defined. If no valid pattern is found the execution 
    terminates abnormally.
    
    The idea is to specify default values which will be
    assigned to each invocations. 
"""
DEFAULT_PARAMETERS = [
        ("(\w*)pk", 1), 
        ("user", "user"),
        ("username", "user"),
        (".+", 1),
        ]


def create_user(name = "user", pwd = "pwd", email = "email@example.com"):
    form = UserCreationForm(
                {'username': name,
                 'password1': pwd,
                 'password2': pwd,
                 'email': email,
                 })
    if not form.is_valid():
        raise AttributeError('Form should be valid: %s' % form.errors)
    user = form.save()
    if user is None:
        raise AssertionError('Created User should not be None.')
    return user


def is_resolver(url):
    """ Determine if the given instance points to a single
        url o to a set. Sets are instances of RegexURLResolver
        
        @param url: the django.conf.urls.defaults.url 
    """
    return isinstance(url, RegexURLResolver)


def call_view(url, request, assignments):
    """ Creates the kwargs with which the url will be invoked
    
        @param url: @param url: the django.conf.urls.defaults.url
        @param request: the web request which will be used to invoke the url
        @param assignments: a collection of (regex, value) used as a default 
                value for the invocation. Examples are "(\w*)pk", 1) 
                or ("user", "mark")
    """
    kwargs = url.default_args
    kwargs["request"] = request
    for key in url.regex.groupindex:
        for pattern in assignments:
            result = pattern[0].match(key)
            if result != None:
                kwargs[key] = pattern[1]
                break
        else:
            raise AssertionError("Unassigned key: %s" % key)
    
    return kwargs


def create_request(user = None, method = "GET"):
    """ Creates a mock request authenticating the given User
    
        @param user: the user which has to be authenticated.
        @return: an instance of HttpRequest.
    """
    request = HttpRequest()
    session_store = SessionStore(session_key = '1234567890qwerty')
    session_store.save()
    session = Session.objects.get(pk = session_store.session_key) 
    request.session = session
    request.META['REMOTE_ADDR'] = "127.0.0.1"
    if user == None:
        from django.contrib.auth.models import AnonymousUser
        user = AnonymousUser()
    request.user = user
    request.method = method
    return request